<template>
    <div>
        <el-card class="box-card">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline" >
                <el-form-item>
                    <el-input v-model="searchForm.sname" placeholder="学生姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchForm.addr" placeholder="学生住址"></el-input>
                </el-form-item>
                <el-form-item label="活动区域">
                    <el-select v-model="searchForm.cid" placeholder="所在班级">
                        <el-option label="所有班级" value="0"></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search()" icon="el-icon-search">查询</el-button>
                    <el-button type="success" @click="add()" icon="el-icon-plus">添加</el-button>
                    <el-button type="danger" @click="handleDelete()" icon="el-icon-minus">批量删除</el-button>
                </el-form-item>
            </el-form>
            ---{{multipleSelection}}
            <el-table
                    :data="students"
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                <el-table-column
                        type="selection"
                        width="50">
                </el-table-column>
                <el-table-column
                        label="学号"
                        prop="sid"
                        align="center"
                        width="100">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        prop="sname"
                        align="center"
                        width="120">
                </el-table-column>
                <el-table-column
                        label="性别"
                        prop="sex"
                        align="center"
                        width="120">
                </el-table-column>
                <el-table-column
                        label="年龄"
                        prop="age"
                        align="center"
                        width="120">
                </el-table-column>
                <el-table-column
                        label="住址"
                        prop="addr"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="所在班级"
                        prop="cname"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="success"
                                plain
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                plain
                                @click="handleDelete(scope.row.sid)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" align="left">
            --{{studForm}}
            <el-form :model="studForm" :rules="rules" ref="ruleForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                    <el-input v-model="studForm.sname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
                        <el-radio label="男" v-model="studForm.sex"></el-radio>
                        <el-radio label="女" v-model="studForm.sex"></el-radio>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model.number="studForm.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="studForm.addr" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                    <el-select v-model="studForm.cid" placeholder="选择班级" style="width: 100%">
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">确 定</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
    export default {
        name: "Student",
        data(){
            const checkAge = (rule,value,callback)=>{
                if (!value) {
                    return callback(new Error('年龄不能为空'));
                }else if (isNaN(value)){
                    return callback(new Error('年龄必须是数字'));
                }else{
                    return callback();
                }
            };
            return {
                students: [],               //每页记录集合
                page:1,                     //代表当前页
                total:100,                  //代表总记录数
                pageSize:5,                 //代表每页大小
                searchForm:{},              //代表搜索的学生对象
                classes:[],                 //所有的班级
                title:'添加学生',            //对话框标题
                dialogFormVisible:false,    //是否显示对话框
                formLabelWidth:'120px',     //对话框中提示文字的宽度
                studForm:{},                //代表要添加或修改的学生对象
                multipleSelection: [],      //多选得到的数组
                rules:{
                    sname:[{
                       required:true,message:'请输入学生姓名',trigger:'blur'
                    }],
                    sex:[{
                         required: true, message: '请选择性别', trigger: 'change'
                    }],
                    age:[{
                        validator:checkAge,trigger:'blur'   //validator使用自定义校验规则
                    }],
                    addr:[{
                        required:true,message:'请输入学生住址',trigger:'blur'
                    }],
                    cid:[{
                        required:true,message:'请选择班级',trigger:'blur'
                    }],
                },
            }
        },
        created() {
            // 1、查询所有学生
            this.findAllStudents();
            //2、分页查询学生
            // this.findPage(this.page,this.pageSize);
            //查询所有班级
            this.findAllClasses();
            //4、分页带条件查询
            this.search();
        },
        methods:{
            //0.查询所有学生
            findAllStudents(){
                this.axios.get(`/student?cmd=list`).then(data=>{
                    console.log("data:"+data.data);
                    //
                    this.students = data.data;
                })
            },
            // 1、分页查询所有学生
            findPage(page,pageSize){
                this.axios.get(`/student?cmd=findPage&page=${this.page}&pageSize=${this.pageSize}`).then(data=>{
                    console.log("data:"+data.data);
                    //1.1、为总记录数赋值
                    this.total = data.data.total;
                //    1.2、为当前页的记录集合赋值
                    this.students = data.data.rows;
                })
            },
            //2、每页大小(pageSize)改变时触发
            handleSizeChange(pageSize) {
                console.log(`每页 ${pageSize} 条`);
                this.pageSize = pageSize;
               // this.findPage(this.page,this.pageSize);
                this.search();
            },
            //每页(page)改变时触发
            handleCurrentChange(page) {
                console.log(`当前页: ${page}`);
                this.page = page;
               // this.findPage(this.page,this.pageSize);
                this.search();
            },
            //4、查询所有的班级列表
            findAllClasses(){
                this.axios.get("/classes").then(data=>{
                    this.classes = data.data;
                })
            },
        //    5、条件查询带分页
            search(){
                this.axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+JSON.stringify(this.searchForm)).then(data=>{
                    //1.1、为总记录数赋值
                    this.total = data.data.total;
                    //    1.2、为当前页的记录集合赋值
                    this.students = data.data.rows;
                })
            },
        //    6、添加学生
            add(){
                //修改标题
                this.title = "添加学生";
                //打开对话框
                this.dialogFormVisible=true;
                //清空修改显示的数据
                this.studForm = {};
            },
            //7、编辑学生
            handleEdit(index, row) {
                console.log(index, row);
                //修改标题
                this.title = "修改学生";
                //打开对话框
                this.dialogFormVisible = true;
                //将当前修改的数据赋值给studForm
                this.studForm = row;
            },
            //8、删除学生
            handleDelete(sid) {
                let _this=this;
                //定义要删除的id数组
                let ids = [];
               //一次性删除一个或批量删除
               //  if (sid){
               //      ids.push(sid);
               //  }else {
               //      // ids = this.multipleSelection.map(m=>{
               //      //     return m.sid;
               //      // })
               //      ids = this.multipleSelection.map(m=>m.sid);
               //  }
                ids=sid?[sid]:this.multipleSelection.map(m=>m.sid);
                //提示
                this.$confirm(`是否真的要删除学号为[${ids}]的学生?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.axios.get(`/student?cmd=deleteByIds&ids=${ids}`).then(data=>{
                        if (data.data.code==0){
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                onClose(){
                                  _this.search();
                                },
                            });
                        }
                    })
                }).catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: '已取消删除'
                    // });
                });

                console.log("ids",ids);

            },
            //9、保存学生(添加/修改)
            save(){
                //根据sid判断添加还是修改
                let url = "/student?cmd=add";
                if (this.studForm.sid){
                    url = "/student?cmd=update";
                }
                //表单验证通过就提交数据
                this.$refs['ruleForm'].validate(valid=>{
                    let _this = this;
                    if (valid){
                        this.axios.post(url,"stud="+JSON.stringify(this.studForm)).then(data=>{
                            if (data.data.code==0){
                                console.log("data:"+data);
                                //关闭对话框
                                this.dialogFormVisible = false;
                                //弹出消息框
                                this.$message({
                                    message: `恭喜你，${this.studForm.sid ? '修改' : '添加'}学生成功`,
                                    type: 'success',
                                    onClose(){
                                        //刷新页面
                                        _this.search();
                                    },
                                });

                            }
                        })
                    }
                })

            },
            //处理多选
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

        }
    }
</script>

<style scoped>
    .el-pagination{
        margin-top: 20px;
        text-align: right;
    }
    .el-form{
        text-align: left;
    }
</style>